package com.helloandroid.services

import androidx.core.content.edit
import com.helloandroid.MyApplication
import com.helloandroid.tools.IntentValue
import com.helloandroid.tools.MyTimeUtils

class LocalBuShuInfo(
        var lastAwardTimeMs: Long = 0L, // 上次领奖时间
        var lastTimeMs_Remind: Long = 0L,
        var bFlagBs: Boolean = true,
) {

    companion object {
        const val PrefBuShu = "s_pref_bs"
        const val KeyLastAwardTimeMs = "key_last_award_time"
        const val KeyLastTimeMs_Remind = "key_last_time_remind"
        const val KeyFlagBs = "key_flag_bs"
    }

    fun init() {
        val pref = MyApplication.getPerference(PrefBuShu)

        // 上次领取完成步数奖励的时间
        lastAwardTimeMs = pref.getLong(KeyLastAwardTimeMs, 0L)

        // 上次提醒时间
        lastTimeMs_Remind = pref.getLong(KeyLastTimeMs_Remind, 0L)
        bFlagBs = pref.getBoolean(KeyFlagBs, true)
    }

    fun clearData() {
        MyApplication.getPerference(PrefBuShu).edit(commit = true) {
            clear()
        }
    }

    fun check(service: ServerService, curTimeMs: Long): Boolean {
        // 1. 玩家开了提醒
        // 2. 今天已经完成 并且 今天还没有提醒
        if (bFlagBs) {

            val curDayTime = MyTimeUtils.dayTimeString(curTimeMs)

            // 今天是否提醒过?
            val remindDayTime = MyTimeUtils.dayTimeString(lastTimeMs_Remind)
            if (curDayTime == remindDayTime){
                return false
            }

            // 判断今天是否领取了步数目标奖励
            if (curDayTime == MyTimeUtils.dayTimeString(lastAwardTimeMs)) {
                return false
            }

            // 判断是否可以领取,可以领取才提醒
            if (service.localUserInfo.bs < service.localUserInfo.bsTarget){
                return false
            }

            // 发送通知
            service.sendRemindNotify("步数成就已达成", "恭喜,您的步数金币已到账,请领取!", IntentValue.Int_BuShu)
            MyApplication.getPerference(PrefBuShu).edit(commit = true) {
                putLong(KeyLastTimeMs_Remind, curTimeMs)
            }
            lastTimeMs_Remind = curTimeMs
            return true
        }
        return false
    }

    fun saveDakaTime(time:Long){
        MyApplication.getPerference(PrefBuShu).edit(commit = true){
            putLong(KeyLastAwardTimeMs,time)
        }
        lastAwardTimeMs = time
    }

    fun updateFlag(newFlag:Boolean){
        if (bFlagBs != newFlag){
            bFlagBs = newFlag
            MyApplication.getPerference(PrefBuShu).edit(commit = true){
                putBoolean(KeyFlagBs,newFlag)
            }
        }
    }
}